package cn.easypay.shop.executor;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class demo {

    public static final String MERCHANT_NO = "TEST20210520";
    public static final String SIGN_KEY = "59a31ae47ff8fbb423ba4dc1db4d92";

    public static final String URL = "https://szk.app.lexiangaysh.cn/open/api/person/risk/report/query";

    public static void main(String[] args) {
        TreeMap<String, Object> treeMap = new TreeMap();
        treeMap.put("merchantNo", MERCHANT_NO);
        treeMap.put("timeStamp", Calendar.getInstance().getTimeInMillis());
        treeMap.put("templateId", "16");
        treeMap.put("realName", "张三");
        treeMap.put("idCardNo", "510802198712345678");
        treeMap.put("mobile", "13912345678");
        treeMap.put("sign", sign(treeMap, SIGN_KEY));
        String doPost = doPost(URL, treeMap);
        System.out.println("doPost: " + JSONObject.fromObject(doPost));
    }

    //
    private static String doPost(String apiUrl, Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;
        try {
            List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if(entry.getValue() != null) {
                    NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
                            .getValue().toString());
                    pairList.add(pair);
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return httpStr;
    }

    /**
     * 签名
     * @param treeMap
     * @param signKey
     * @return
     */
    public static String sign(TreeMap<String, Object> treeMap, String signKey) {
        byte[] hash;
        try {
            //将参数使用ASCII排序
            StringBuilder sb = new StringBuilder();
            for(Map.Entry<String, Object> et : treeMap.entrySet()) {
                sb.append(et.getKey() + "=" + et.getValue() + "&");
            }
            sb.append("signKey=" + signKey);
            //创建一个MD5算法对象，并获得MD5字节数组,16*8=128位
            hash = MessageDigest.getInstance("MD5").digest(sb.toString().getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }
        //转换为十六进制字符串
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString().toUpperCase();
    }

}
